﻿using CloudMusic.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace CloudMusic.Helper
{
    public class CommonHelper
    {
        #region margin 设置
        public static Thickness marginTop(int num)
        {
            Thickness gridTop = new Thickness();
            gridTop.Top = num;
            return gridTop;
        }

        public static Thickness marginLeft(int num)
        {
            Thickness gridLeft = new Thickness();
            gridLeft.Left = num;
            return gridLeft;
        }
        #endregion

        #region API获取数据转化为实体
        public static T GetEquipList<T>(int orgId, string url)
        {
            string Url = url;
            var content = new FormUrlEncodedContent(new Dictionary<string, string>()
                {
                        { "orgId",orgId.ToString()}
                 });

            var resultRpt = ExecuteInterfaceByUrl(Url, content);
            string json = JsonConvert.SerializeObject(resultRpt);
            JsonReader reader = new JsonTextReader(new StringReader(json));
            while (reader.Read())
            {
                json = reader.Value.ToString();
            }
            JObject jo = (JObject)JsonConvert.DeserializeObject(json);
            T d = JsonConvert.DeserializeObject<T>(jo.ToString());
            return d;
        }


        public static string GetEquipList(int orgId, string url)
        {
            string Url = url;
            var content = new FormUrlEncodedContent(new Dictionary<string, string>()
                {
                        { "orgId",orgId.ToString()}
                 });

            var resultRpt = ExecuteInterfaceByUrl(Url, content);
            string json = JsonConvert.SerializeObject(resultRpt);
            return json;

        }

        protected static string ExecuteInterfaceByUrl(string url, FormUrlEncodedContent para)
        {
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };

            using (var http = new HttpClient(handler))
            {
                var responseRpt = http.PostAsync(url, para).Result;
                var resultRpt = responseRpt.Content.ReadAsStringAsync().Result;
                return resultRpt;
            }
        }
        #endregion

        #region 单位转化为 万
        public static string toNumber(string number)
        {
            string str = "";
            float intNum = float.Parse(number);
            if (intNum <= 0)
            {
                str = "";
            }
            else if (intNum < 10000)
            {
                str = number.ToString();
            }
            else
            {
                double d = (double)intNum;
                //将数字转换成万
                double num = d / 10000;
                //四舍五入保留小数点后一位
                str = Math.Round(num).ToString();
                str = str + "万";
            }
            return str;
        }
        #endregion

        #region 资源图转换
        public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
        {
            BitmapImage bitmapImage = new BitmapImage();
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                bitmap.Save(ms, bitmap.RawFormat);
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = ms;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                bitmapImage.Freeze();
            }
            return bitmapImage;
        }
        #endregion

        #region 产生随机数
        // Number随机数个数
        // minNum随机数下限
        // maxNum随机数上限
        public static int[] GetRandomArray(int Number, int minNum, int maxNum)
        {
            int j;
            int[] b = new int[Number];
            Random r = new Random();
            for (j = 0; j < Number; j++)
            {
                int i = r.Next(minNum, maxNum + 1);
                int num = 0;
                for (int k = 0; k < j; k++)
                {
                    if (b[k] == i)
                    {
                        num = num + 1;
                    }
                }
                if (num == 0)
                {
                    b[j] = i;
                }
                else
                {
                    j = j - 1;
                }
            }
            return b;
        }
        #endregion

        #region 滚动条联动
        public static void RunScorllView(object sender, MouseWheelEventArgs e)
        {
            if (e.Handled) return;
            e.Handled = true;
            var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta)
            {
                RoutedEvent = UIElement.MouseWheelEvent,
                Source = sender
            };
            var parent = ((Control)sender).Parent as UIElement;
            parent?.RaiseEvent(eventArg);
        }
        #endregion

        public static string SetLength(string str)
        {
            if (str.Length > 20)
            {
                return str.Substring(0, 18) + "...";
            }
            else
            {
                return str;
            }
        }

        #region 网路读取json
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string Get(string Url)
        {
            string retString = "";
            try
            {
                //System.GC.Collect();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Proxy = null;
                request.KeepAlive = false;
                request.Method = "GET";
                request.ContentType = "application/json; charset=UTF-8";
                request.AutomaticDecompression = DecompressionMethods.GZip;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                retString = myStreamReader.ReadToEnd();

                myStreamReader.Close();
                myResponseStream.Close();

                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            catch (Exception ex) { retString = ex.Message; }
            return retString;
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Data"></param>
        /// <param name="Referer"></param>
        /// <returns></returns>
        public static string Post(string Url, string Data, string Referer)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.Referer = Referer;
            byte[] bytes = Encoding.UTF8.GetBytes(Data);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;
            Stream myResponseStream = request.GetRequestStream();
            myResponseStream.Write(bytes, 0, bytes.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
            return retString;
        }
        /// <summary>
        /// 字符串转化为json
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ConvertStringToJson(string str)
        {
            //格式化json字符串
            JsonSerializer serializer = new JsonSerializer();
            TextReader tr = new StringReader(str);
            JsonTextReader jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return str;
            }
        }
        #endregion

        #region 歌单页面歌单播放数 歌手类型 usertype=200-星星，2-网易V，4-网易云音乐人
        public static string GetPlayCount(long count)
        {
            if (count < 100000)
            {
                return count.ToString();
            }
            else
            {
                return toNumber(count.ToString());
            }
        }
        public static string GetStarsVis(int userType)
        {
            if (userType == 200)
            {
                return "Visible";
            }
            else
            {
                return "Collapsed";
            }
        }
        public static string GetVVis(int userType)
        {
            if (userType == 2)
            {
                return "Visible";
            }
            else
            {
                return "Collapsed";
            }
        }
        public static string GetMusicVis(int userType)
        {
            if (userType == 4)
            {
                return "Visible";
            }
            else
            {
                return "Collapsed";
            }
        }
        #endregion

        #region 其他通用事件
        /// <summary>
        /// 格式化付费
        /// </summary>
        /// <param name="pay"></param>
        /// <returns></returns>
        public static int SetPayInfo(Int32 pay)
        {
            if (pay != 0)
            {
                return pay / 100;
            }
            return 0;
        }

        /// <summary>
        /// 鼠标上移后显示的信息
        /// </summary>
        /// <param name="name"></param>
        /// <param name="h"></param>
        /// <returns></returns>
        public static string GetTitle(string name, List<string> h)
        {
            if (h.Count > 0)
            {
                return name + "(" + h[0].ToString() + ")";
            }
            return name;
        }
        /// <summary>
        /// 是否具有MV
        /// </summary>
        /// <param name="mvId"></param>
        /// <returns></returns>
        public static string GetMvVis(long mvId)
        {
            if (mvId != 0)
            {
                return "Visible";
            }
            return "Collapsed";
        }
        /// <summary>
        /// 是否SQ
        /// </summary>
        /// <param name="maxbr"></param>
        /// <returns></returns>
        public static string GetSQVis(long maxbr)
        {
            if (maxbr == 999000)
            {
                return "Visible";
            }
            return "Collapsed";
        }
        /// <summary>
        /// 是否试听
        /// </summary>
        /// <param name="fee"></param>
        /// <returns></returns>
        public static string GetSTVis(long fee)
        {
            if (fee == 1)
            {
                return "Visible";
            }
            return "Collapsed";
        }
        /// <summary>
        /// 是否VIP
        /// </summary>
        /// <param name="fee"></param>
        /// <returns></returns>
        public static string GetVIPVis(long fee)
        {
            if (fee == 1)
            {
                return "Visible";
            }
            return "Collapsed";
        }
        public static string GetVis(long intStr)
        {
            string str = "Collapsed";
            switch (intStr)
            {
                case 1:
                    str = "Visible";
                    break;
                case 999000:
                    str = "Visible";
                    break;
            }
            return str;
        }
        #endregion
        /// <summary>
        /// 歌曲品质封装
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
        public static List<ChargeInfo> GetChargeInfos(List<ChargeInfoList> ch)
        {
            List<ChargeInfo> chargeInfos = new List<ChargeInfo>();
            for (int i = 0; i < ch.Count; i++)
            {
                chargeInfos.Add(new ChargeInfo
                {
                    Rate = ch[i].rate,
                    ChargeMessage = ch[i].chargeMessage,
                    chargeType = ch[i].chargeType,
                    chargeUrl = ch[i].chargeUrl
                });
            }
            return chargeInfos;
        }
        /// <summary>
        /// 判断是否在喜欢歌曲列表里
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static int CheckLikes(long id)
        {
            int i = 0;
            if (PlayListHelper.UserLikes.Count > 0)
            {
                if (PlayListHelper.UserLikes[0].ids.Count != 0)
                {
                    if (PlayListHelper.UserLikes[0].ids.Any(t => t == id))
                    {
                        i = 1;
                    }
                }
            }
            return i;
        }
    }
}
